<script setup lang="ts">
import { getRegionsById } from '@/api/common'
import { onMounted, ref } from 'vue'

const props = defineProps({
  provinceData: {
    type: Array as () => any[],
    default: () => [
      {
        id: '',
        localName: '请选择',
        children: []
      }
    ]
  },
  pickerSize: {
    type: null,
    default: 4
  },
  headTitle: {
    type: String,
    default: '请选择'
  },
  clearRightIcon: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['funcValue'])
let windowWidth = 0

const clearRightIcon = ref(true)
const scrollLeft = ref(500)
const scrollTop = ref(0)
const enableScroll = ref(true)
const tabCurrentIndex = ref(0)
const tabbars = ref(props.provinceData)
const pickersize = ref(props.pickerSize)
const showPicker = ref(false)

defineExpose({ show })
function show() {
  showPicker.value = true
  if (tabbars.value[0].children.length === 0) {
    getRegionsById(0).then((res) => {
      tabbars.value[0].children = res.data.result
    })
  }
  windowWidth = window.innerWidth
}

function hide() {
  console.log('隐藏')
  showPicker.value = false
}

function changeTab(index: number) {
  setScroll(index)
  tabCurrentIndex.value = index
  setTimeout(() => {
    getScroll(`show${index}`)
  }, 10)
}

async function getElSize<T extends Element>(id: string): Promise<DOMRect | undefined> {
  return new Promise<DOMRect | undefined>((res: any) => {
    const el = document.querySelector(`#${id}`)
    if (el instanceof HTMLElement) {
      const rect = el.getBoundingClientRect()
      res(rect)
    }
  })
}

// 选中城市
async function changCity(index: number, item: any) {
  if (tabbars.value[index].id !== item.id) {
    tabbars.value[index].localName = item.name
    tabbars.value[index].id = item.id

    tabbars.value[index].center = item.center

    if (index < tabbars.value.length - 1) tabbars.value.splice(index + 1, tabbars.value.length - index - 1)

    if (tabbars.value.length < pickersize.value) {
      const data = await getRegionsById(item.id)
      if (data.data.result.length === 0) {
        emit('funcValue', tabbars.value)
        hide()
      } else {
        const current = {
          localName: '请选择',
          id: '',
          children: data.data.result
        }
        tabbars.value.push(current)
        tabCurrentIndex.value++
        scrollTop.value = 0
      }
    } else {
      emit('funcValue', tabbars.value)
      hide()
    }
  }
}

async function setScroll(index: number) {
  let width = 0
  let nowWidth = 0
  for (let i = 0; i <= index; i++) {
    const result = await getElSize(`tab${i}`)
    if (result) {
      width += result.width
      if (i === index) nowWidth = result.width
    }
  }
  scrollLeft.value = width + nowWidth > windowWidth ? width + nowWidth : 0
}

function getScroll(id: string) {
  const panelScrollBox = document.querySelector('.panel-scroll-box')
  if (panelScrollBox instanceof HTMLElement) {
    const data = panelScrollBox.getBoundingClientRect()
    const el = document.querySelector(`#${id}`)
    if (el instanceof HTMLElement) {
      const res = el.getBoundingClientRect()
      scrollTop.value = res.top - data.top
    }
  }
}

onMounted(() => {
  windowWidth = window.innerWidth
})
</script>

<template>
  <div>
    <div class="mask" :class="{ maskShow: showPicker }" catchtouchmove="true" @click="hide" @touchmove.stop.prevent>
      <div @click.stop.prevent class="picker-content" :class="{ 'picker-show': showPicker }">
        <div class="city-head" catchtouchmove="true" @click.stop.prevent @touchmove.stop.prevent>
          <div class="city-head-title">
            {{ headTitle }}
          </div>
          <div style="position: absolute; right: 30rpx; top: 26rpx">
            <nut-icon v-if="clearRightIcon" size="16" color="#cccccc" name="close" @click="hide" />
          </div>
        </div>
        <scroll-view
          id="nav-bar"
          class="nav-bar"
          :scroll-x="true"
          :scroll-with-animation="true"
          :scroll-left="scrollLeft">
          <div
            v-for="(item, index) in tabbars"
            :id="`tab${index}`"
            :key="index"
            class="nav-item"
            :class="{ current: index === tabCurrentIndex }"
            @click="changeTab(index)">
            <span class="nav-bar-title">{{ item.localName }}</span>
          </div>
        </scroll-view>
        <div class="city_content">
          <scroll-view
            class="panel-scroll-box"
            :scroll-y="enableScroll"
            :cscroll-top="scrollTop"
            :current="tabCurrentIndex"
            :scroll-top="scrollTop">
            <template v-for="(item, index) in tabbars[tabCurrentIndex].children" :key="index">
              <div class="flex-row-c-c" @click="changCity(tabCurrentIndex, item)">
                <span class="city-text" :class="{ color: tabbars[tabCurrentIndex].id === item.id }">
                  {{ item.name }}
                </span>
                <nut-icon
                  v-if="tabbars[tabCurrentIndex].id === item.id"
                  :id="`show${tabCurrentIndex}`"
                  class="is-check"
                  size="14"
                  name="Check" />
              </div>
            </template>
          </scroll-view>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.mask {
  visibility: hidden;
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.6);
  opacity: 0;
  transition: all 0.3s ease;
}

.maskShow {
  visibility: visible;
  opacity: 1;
}

.picker-content {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #ffffff;
  transition: all 0.3s ease;
  transform: translateY(100%);
  z-index: 3000;
}

.picker-show {
  transform: translateY(0);
}

.city-head {
  width: 750rpx;
  height: 88rpx;
  flex-direction: column;
  border-bottom-width: 1px;
  border-bottom-color: #f4f4f4;
  border-bottom-style: solid;
  position: relative;
  display: flex;
  align-items: center;
}

.city-head-title {
  font-size: 15px;
  line-height: 88rpx;
  align-items: center;
  /* #ifndef APP-NVUE */
  text-align: center;
  /* #endif */
}

.clearRightIcon {
  position: absolute;
  right: 15px;
  top: 12px;
  font-size: 10px;
  color: #bebebe;
}

.nav-bar {
  position: relative;
  z-index: 10;
  height: 90rpx;
  white-space: nowrap;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  background-color: #fff;
}

.nav-item {
  /* #ifndef APP-NVUE */
  display: inline-flex !important;
  /* #endif */
  /* #ifdef APP-NVUE */
  flex-direction: row !important;
  /* #endif */
  width: 170rpx;
  padding: 7px 0px;
  line-height: 26px;
  align-items: center;
  justify-content: center;
  color: $main-color;
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nav-bar-title {
  font-size: 12px;
}

.current {
  color: $main-color;
  border-color: $main-color;
  border-bottom-width: 4rpx;
  border-bottom-style: solid;
}

.current:after {
  width: 50%;
}

.panel-scroll-box {
  height: 516rpx;
  margin-top: 8px;
}

.flex-row-c-c {
  /* #ifndef APP-NVUE */
  display: block;
  /* #endif */
  /* #ifdef APP-NVUE */
  flex-direction: row;
  /* #endif */
  padding-left: 25px;
}

.city-text {
  /* #ifdef APP-NVUE */
  flex-direction: row;
  /* #endif */
  height: 35px;
  line-height: 35px;
  font-size: 13px;
}

.hide {
  opacity: 0;
}

.is-check {
  color: $main-color;
  /* #ifndef APP-NVUE */
  display: inline-flex !important;
  /* #endif */
  /* #ifdef APP-NVUE */
  flex-direction: column;
  /* #endif */
  margin-right: 5px;
  vertical-align: middle;
}

.color {
  color: $main-color;
}

icon {
  margin-left: 40rpx;
}
</style>
